package com.az.order.controller;


import com.az.miaoapi.exception.BaseException;
import com.az.miaoapi.response.ResponseCode;
import com.az.miaoapi.vo.Null;
import com.az.miaoapi.vo.TheVo;
import com.az.order.domain.dto.OrderSearchDto;
import com.az.order.domain.po.OrderDetail;
import com.az.order.domain.vo.OrderVoList;
import com.az.order.service.OrderDetailService;
import com.az.order.service.OrdersService;
import com.az.servicecommon.util.BaseResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.retry.annotation.Retryable;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;


/**
 * @author zj
 * @time 2024/8/23 22:49
 */
@RestController
@RequestMapping("/order")
@BaseResponse
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private CacheManager cacheManager;

//
    @PutMapping("/orders")
    @PreAuthorize("hasAnyAuthority({'loginUser'})")
    public TheVo postOrders(@RequestParam(value = "orderId") Long orderId,Principal principal) {
        // 获取当前登录用户
        Long userId = Long.valueOf(principal.getName());
        // 调用服务层方法
        return orderService.postOrders(orderId, userId);
    }

//删除订单
    @DeleteMapping
    @Retryable
    @PreAuthorize("hasAnyAuthority({'loginUser'})")
    public TheVo deleteOrder(@RequestParam Integer orderId) {
    // 获取缓存
    Cache cache = cacheManager.getCache("orderCache");
    // 删除订单详情
    QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("order_id", orderId);
    orderDetailService.remove(queryWrapper); // 根据订单ID删除对应的订单详情
    // 删除订单
    boolean isRemoved = orderService.removeById(orderId); // 根据订单ID删除订单
    if (isRemoved) {
        // 清除缓存中的相关数据
        if (cache != null) {
            cache.evictIfPresent(orderId);
        }
        log.info("删除成功");
        return new Null(); // 返回成功结果
    } else {
        throw new BaseException(ResponseCode.DELETE_ORDER_FAILED);
    }
}
    @PostMapping
    @PreAuthorize("hasAnyAuthority({'loginUser'})")
    public OrderVoList getOrder(OrderSearchDto orderSearchDto, Principal principal) {
        // 获取用户名
        Long userId = Long.valueOf(principal.getName());
        return orderService.getOrder(orderSearchDto, userId);
    }

}
